import Taro from "@tarojs/taro";
import {AUTH_LEVEL, doAuth} from "../auth/authFilter";
import {getGlobalData, setGlobalData} from "../../global.d";
import {toast} from "../../utils";

const db = Taro.cloud.database();

export function login() {
  // 先登录，获取openId
  Taro.cloud
    .callFunction({
      name: 'login'
    })
    .then(async res => {
      // 获取openId成功，根据openId查询用户信息
      let openId = res.result.OPENID;
      setGlobalData('openId', openId);
      let user = await getUser(openId);
      // 该用户未注册，自动注册
      if (!user) {
        register();
      }
      doAuth('');
    });
}

export function register() {
  // 插入用户
  return db.collection('user')
    .add({
      data: {
        createTime: new Date(),
        userClass:[
          {
            className:'【默认加入】酷班级功能展示一班',
            classKey:'00000001',
            type:AUTH_LEVEL.USER
          }
        ],
        userLastTimeClass:{
          className:'【默认加入】酷班级功能展示一班',
          classKey:'00000001',
          type:AUTH_LEVEL.USER
        }
      }
    })
    .then(res => {
      console.log(res);
    })
    .catch(err => {
      toast('自动注册失败');
      console.error(err);
    })
}

export function getUser() {
  let openId = getGlobalData('openId');
  return db.collection('user')
    .where({
      _openid: openId,
    }).get().then(({data}) => {
      if (data.length > 0) {
        return data[0];
      }
      return null;
    });
}
